package com.longtop.framework.sys.file.dispatcher;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.longtop.framework.sys.file.context.FileContext;
import com.longtop.framework.sys.file.supports.UpLoadUtils;
import com.longtop.framework.sys.file.supports.UpLoadedFiles;
import com.longtop.framework.sys.file.supports.UploadFile;
import com.longtop.framework.util.SpringBeanFactory;
import com.longtop.framework.util.StringUtil;

public class FileDispatcher implements Filter {
	private String sessionId = "user.session";// 用户session对象
	private String uploadbean = "cosUpload";// 普通上传的beanID
	private String exceptURL = "html,htm";// 排除进入dispatcher的页面

	private UpLoadedFiles uploadFile(HttpServletRequest request) {
		// 传入的上传配置文件的beanID，具体见fileBean-service.xml；
		String uploadBean = StringUtil.getString(request.getParameter("uploadbean"));
		if (!uploadBean.equals("")) {
			uploadbean = uploadBean;// 若传入的beanID为空，则默认为普通的上传。
		}
		UpLoadUtils uploadUtils = SpringBeanFactory.getBean(uploadbean);
		// 解析上传文件重要方法：
		UpLoadedFiles ups = uploadUtils.uploadFile(request);

		// 若为空，则为普通文件上传：
		if (ups != null) {
			UploadFile[] uploadFilesArray = ups.getUploadFiles("filename");
			for (int i = 0; i < uploadFilesArray.length; i++) {
				UploadFile up = uploadFilesArray[i];
				if (uploadUtils.getExcelAnalyser() == null) {
					if (up != null) {
						// 文件保存到数据库操作：
						// FileBean fb = new FileBean();
						// fb.setClientFilename(up.getFileName());
						// fb.setFileDesc(ups.getMyUpload().getParameter("fileDesc"));
						// fb.setFileExt(up.getFileExt());
						// fb.setSpringBean(uploadbean);
						// fb.setFileSize(up.getFileSize());
						// fb.setModuleId(ups.getMyUpload().getParameter("module"));
						// fb.setObjectid(ups.getMyUpload().getParameter("objectid"));
						// fb.setUploadUser(((SessionObject) request.getSession().getAttribute(Constants.SESSION_OBJECT)).getUserId());
						// fb.setUploadTime(new Date());
						// fb.setServerPath(up.getSavePath());
						// fb.setServerFilename(up.getSaveFileName());
						// IFileService fileService = SpringBeanFactory.getBean(IFileService.BEAN_ID);
						// fileService.save(fb);
					}
				}
			}
		}
		return ups;

	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest requestEx = (HttpServletRequest) request;
		String uri = requestEx.getRequestURL().toString();

		String[] urlExcept = StringUtil.split(exceptURL, ",");
		boolean bool = true;
		for (int i = 0; i < urlExcept.length; i++) {
			if (uri.endsWith(urlExcept[i])) {
				bool = false;
				break;
			}
		}

		if (bool) {
			Map<String, Object> sessionMap = new HashMap<String, Object>();
			sessionMap.put(sessionId, requestEx.getSession());
			UpLoadedFiles ups = null;
			String content_type = request.getContentType();
			if (content_type != null && content_type.indexOf("multipart/form-data") != -1) {

				ups = uploadFile(((HttpServletRequest) request));
				// 将UpLoadedFiles 设置到sessionMap里，
				sessionMap.put("upLoadedFiles", ups);

			}

			// 设置sessionMap 到FileContext里：用于之后业务层取UpLoadedFiles类
			FileContext fileContext = new FileContext(sessionMap);
			FileContext.setFileContext(fileContext);
		}

		try {
			chain.doFilter(request, response);
		} finally {
			FileContext.setFileContext(null);
		}

	}

	public void init(FilterConfig arg0) throws ServletException {
		String ub = StringUtil.getString(arg0.getInitParameter("uploadbean"));
		uploadbean = ub.equals("") ? uploadbean : ub;
		String url = StringUtil.getString(arg0.getInitParameter("exceptURL"));
		exceptURL = url.equals("") ? exceptURL : url;

	}

	public void destroy() {

	}

}
